package util;

import java.io.File;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *解析sql的xml配置文件。这些文件均在com/sql文件夹下，命名规则为：dang-xxx.xml
 */
@SuppressWarnings("unchecked")
public class SqlConfigurationFileUtil {
	private static Map<String, Element> eleMap = new HashMap<String, Element>();
	
	private static Logger log = Logger.getLogger(SqlConfigurationFileUtil.class);
	
	static {
		log.info("start parsing xml configuration file...");
		File file = null;
		try {
			file = new File(SqlConfigurationFileUtil.class.getClassLoader().getResource("/dao/sql").toURI());
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
		if (!file.exists()) {
			log.info("cannot parse xml configuration file,dao/sql folder does not exist...");
		} else {
			File[] xmlFiles = file.listFiles();
			if (xmlFiles.length == 0) {
				log.info("no xml configuration file found...");
			} else {
				log.info("there are " + xmlFiles.length + " xml configuration files...");
				//parse xml file
				SAXReader reader = new SAXReader();
				for (int i = 0; i < xmlFiles.length; i++) {
					File xml = xmlFiles[i];
					try {
						log.info("parse " + xml.getName() + " begin...");
						Document doc = reader.read(xml);
						//assuming that there are root element and sub elements
						Element root = doc.getRootElement();
						List<Element> elements = root.elements();
						if (elements != null && elements.size() > 0) {
							for (int j = 0; j < elements.size(); j++) {
								Element ele = elements.get(j);
								eleMap.put(xml.getName() + ele.attributeValue("id"), ele);
							}
						}
						log.info("parse " + xml.getName() + " end...");
					} catch (Exception e) {
						log.error("parse " + xml.getName() + " error.Detail message is " + e.getMessage());
					}
					
				}
			}
		}
	}
	
	public static Element getElement(String key){
		return eleMap.get(key);
	}

}
